<?php

namespace app\admin\controller\dealer;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="待发货订单列表")
 */
class DeliveryOrder extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\mall\Order();
        
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            // 发货数量筛选
            $numWhere = 'goods_num + gift_num > ?';
            $sum_order_goods = 0;
            foreach ($where as $k => $v) {
                if ($v[0] == 'goods_num') {
                    if ($v[2] == 1) {
                        $numWhere = 'goods_num + gift_num < ?';
                        $sum_order_goods = 10;
                    } else if ($v[2] == 2) {
                        $numWhere = 'goods_num + gift_num >= ?';
                    }
                    unset($where[$k]);
                }
            }
            $orderWhere = [
                'pay_status' => 1, // 支付类型 {select}  (0:未支付 ,1:已支付)
                'refund_status' => 0, // 退款类型 {select}  (0:未退款 ,1:已退款)
                'batch_status' => 0, // 批次状态 {select}  (0:未导出 ,1:已导出)
                'indent_status' => 0, // 订购状态 {select}  (0:正常 ,1:订购)
            ];
            $count = $this->model
                ->where($where)
                ->where($orderWhere)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($orderWhere)
                ->whereRaw($numWhere, [$sum_order_goods]) //发货数量筛选
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
                $goodsModel = new \app\admin\model\mall\Goods;
                $goodsData = $goodsModel->where('is_default',1)->find();
                foreach ($list as $key => &$value) {
                    // $value['salesman_remind'] = ($value['salesman_remind']==0) ?$goodsData['goods_remind']:$value['salesman_remind'];
                    // $value['shop_remind'] = ($value['shop_remind']==0) ?$goodsData['goods_remind']:$value['shop_remind'];
                    $value['goods_name'] = $goodsData->name;
                    $value['goods_images'] = $goodsData->images;
                }
            // print_r($list); exit;
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => count($list),
                'data'  => $list,
            ];
            return json($data);
        }
        $this->layoutBgColor();
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        // $this->success('请选择导出订单');
        // print_r($this->request->get()); exit;
        $order_ids = $this->request->param('ids') ??'';
        $create_time = time();
        $order_batch = $this->request->param('order_batch') ??date('Ymd',$create_time).$create_time;
        $orderWhere = [];
        if (!empty($order_ids)) {
           $orderWhere = [
                ['id','in',$order_ids],
                ['batch_status','=',0],
                ['indent_status','=',0],
            ];
        }
        if (!empty($this->request->param('order_batch'))) {
           $orderWhere = [['order_batch','in',$order_batch]];
        }
        if (empty($orderWhere)) {
            $this->error('请选择导出订单');
        }
        // excel头像信息 
        // 快递 批次 物流单号 日期 主播 来源 订单号 收件人 手机号 地址 物品名称 销售清单 实发清单 下单金额 购买 发货 赠送 合并 方式 已付 未付 实收尾款 回款方式 回款确认 物流代收 财务备注
        $goodsModel = new \app\admin\model\mall\Goods();
        $goodsData = $goodsModel->where('is_default',1)->find();
        $header = [
            [0=>' ' ,1=>''],
            [0=>' ' ,1=>''],
            [0=>' ' ,1=>''],
            [0=>' ' ,1=>''],
            [0=>' ' ,1=>''],
            [0=>'快递' ,1=>'logistics_company'],
            [0=>'批次' ,1=>'order_batch'], //自定义数据
            [0=>'物流单号' ,1=>'logistics_number'],
            [0=>'日期' ,1=>'create_time'],
            [0=>'主播' ,1=>'default_anchor'], //默认主播 东亚供销
            [0=>'来源' ,1=>'default_source'], //默认来源 线下
            [0=>'订单号' ,1=>'order_sn'],
            [0=>'收件人' ,1=>'order_name'],
            [0=>'手机号' ,1=>'order_phone'],
            [0=>'地址' ,1=>'order_adress'], //自定义数据
            [0=>'物品名称' ,1=>'goods_name'], //自定义数据
            [0=>'销售清单' ,1=>'order_sales_list'], //自定义数据
            [0=>'实发清单' ,1=>'order_actual_release'], //自定义数据
            [0=>'下单金额' ,1=>'total_amount'],
            [0=>'购买' ,1=>'goods_num'],
            [0=>'发货' ,1=>'order_send_goods'], //自定义数据
            [0=>'赠送' ,1=>'gift_num'],
            [0=>'合并' ,1=>''],
            [0=>'方式' ,1=>'default_way'], //默认方式 线下全款
            [0=>'已付' ,1=>'ok_amount'],
            [0=>'未付' ,1=>'default_no_amount'], //未付 0
            [0=>'实收尾款' ,1=>''],
            [0=>'回款方式' ,1=>''],
            [0=>'回款确认' ,1=>''],
            [0=>'物流代收' ,1=>'default_logistics_amount'], //物流代收 0
            [0=>'财务备注' ,1=>''],
        ];
        $list = $this->model
            ->where($orderWhere)
            // ->limit(100000)
            ->order('id', 'desc')
            // ->fetchsql(true)->select();
            ->select()->toArray();
        // print_r($list); exit;
        if (empty($list)) {
            $this->error('订单已导出,请勿重复操作');
        }
        // [0=>'批次' ,1=>'order_batch'], //自定义数据
        // [0=>'地址' ,1=>'order_adress'], //自定义数据
        // [0=>'物品名称' ,1=>'goods_name'], //自定义数据
        // [0=>'销售清单' ,1=>'order_sales_list'], //自定义数据
        // [0=>'实发清单' ,1=>'order_actual_release'], //自定义数据
        // [0=>'发货' ,1=>'order_send_goods'], //自定义数据
        // $order_batch = time(); //时间作为批次号
        $fileName = '待发货订单'.$order_batch;
        // $fileName = time();
        $orderData = [];
        foreach ($list as $key => &$value) {
            // 默认数据
            $value['default_anchor'] = '东亚供销';
            $value['default_source'] = '线下';
            $value['default_way'] = '线下全款';
            $value['default_no_amount'] = 0.00;
            $value['default_logistics_amount'] = 0.00;
            // 自定义数据
            $value['order_batch'] = $order_batch;
            $value['order_adress'] = $value['province'].$value['city'].$value['area'].$value['order_address'];
            // $value['goods_name'] = $goodsData->name;
            // $value['order_sales_list'] = $goodsData->name.'*'.$value['goods_num'];
            // $value['order_actual_release'] = $goodsData->name.'*' .($value['goods_num']+$value['gift_num']);
            $value['goods_name'] = '小钢炮';
            $value['order_sales_list'] = '小钢炮'.'*'.$value['goods_num'];
            $value['order_actual_release'] = '小钢炮'.'*' .($value['goods_num']+$value['gift_num']);
            $value['order_send_goods'] = $value['goods_num']+$value['gift_num'];
            // 记录批次
            $orderData[] =[
                'id' => $value['id'],
                'order_batch' => $order_batch,
                'batch_status' => ($value['batch_status']<2) ? 1 : 2,
                'update_time' => $create_time,
                'export_time' => $create_time,
            ];
        }
        // print_r($where);
        // print_r($header);
        // print_r($list);
        // exit;
        //事务
        // $this->model->startTrans();
        try {
            if (!$this->model->saveAll($orderData)) {
                // $this->model->rollback();
                throw new \Exception('修改订单失败');
            }
            if (!Excel::exportData($list, $header, $fileName, 'xlsx')) {
                throw new \Exception('导出订单失败');
            }
            
        } catch (\Exception $e) {
            // $this->model->rollback();
            $this->error('操作失败:'.$e->getMessage());
        }
        // $this->model->commit();
        $this->success('操作成功');
    }
}